package org.haredot.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.haredot.constant.RabbitConst;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.amqp.RabbitTemplateConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitConfig {

    /**
     * 将 发送的消息 以 JSON的形式 传入到 Rabbit 中
     * @return
     */
    @Bean
    public MessageConverter messageConverter() {

        ObjectMapper objectMapper = new ObjectMapper() ;

        objectMapper.registerModules(new SimpleModule(), new JavaTimeModule());

        Jackson2JsonMessageConverter jackson2JsonMessageConverter = new Jackson2JsonMessageConverter(objectMapper);

        return jackson2JsonMessageConverter;
    }


    @Bean("haredotLogExchange")
    Exchange haredotLogExchange() {
        // 创建一个 主题交换机
        return ExchangeBuilder.topicExchange(RabbitConst.HAREDOT_LOG_EXCHANGE)
                .durable(true) // 是否拥有存储该交换机
                .build() ;
    }

    @Bean("loginLogQueue")
    Queue loginLogQueue() {
        return QueueBuilder.durable(RabbitConst.LOGIN_LOG_QUEUE)
                .build();
    }

    @Bean("serviceLogQueue")
    Queue serviceLogQueue() {
        return QueueBuilder.durable(RabbitConst.SERVICE_LOG_QUEUE)
                .build();
    }

    @Bean("haredotLogsQueue")
    Queue haredotLogsQueue() {
        return QueueBuilder.durable(RabbitConst.LOGS_ALL_QUEUE)
                .build();
    }

    @Bean
    Binding loginLogQueueAndExchangeBing(@Qualifier("loginLogQueue") Queue loginLogQueue, @Qualifier("haredotLogExchange") Exchange exchange) {
        return BindingBuilder.bind(loginLogQueue).to(exchange)
                .with("*.login.log")
                .noargs();
    }

    @Bean
    Binding serviceLogQueueAndExchangeBing(@Qualifier("serviceLogQueue") Queue serviceLogQueue, @Qualifier("haredotLogExchange") Exchange exchange) {
        return BindingBuilder.bind(serviceLogQueue).to(exchange)
                .with("*.service.log")
                .noargs();
    }

    @Bean
    Binding haredotLogsQueueAndExchangeBing(@Qualifier("haredotLogsQueue") Queue haredotLogsQueue, @Qualifier("haredotLogExchange") Exchange exchange) {
        return BindingBuilder.bind(haredotLogsQueue).to(exchange)
                .with("#")
                .noargs();
    }

}
